﻿#include "Misc.h"
#include <stdexcept>
#include <sstream>
#include <Windows.h>

namespace Base {

	void Debug::Assert(const char* file, int line, bool flag, const std::string& msg) {
		if (!flag)
		{
			// 
			std::stringstream ss;
			ss << "[" << file << ":" << line << "] " << msg << std::endl;
			Debug::ThrowOrMessageBox(ss.str());
		}
	}


	void Debug::ThrowOrMessageBox(const std::string& msg) {
		static bool bThrow = false;
		if (bThrow)
		{
			throw std::runtime_error(msg);
		}
		else {
			MessageBoxA(nullptr, msg.c_str(), "错误", MB_OK);
		}
	}

	void Debug::CheckLastError() {
		auto errorCode = GetLastError();
		if (errorCode > 0)
		{
			std::ostringstream oss;

			// 使用 FormatMessage 转换错误码为字符串  
			LPSTR messageBuffer = nullptr;
			FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);

			// 输出错误信息  
			//std::cout << "[Error-" << errorCode << "]: " << messageBuffer << std::endl;
			oss << "[Error-" << errorCode << "]:" << messageBuffer << std::endl;

			// 释放分配的内存  
			LocalFree(messageBuffer);

			MessageBoxA(nullptr, oss.str().c_str(), "错误", MB_OK);
		}
	}


	//----------------------------------------
	std::string& Trim(std::string &s)
	{
		if (s.empty())
		{
			return s;
		}

		s.erase(0, s.find_first_not_of(" "));
		s.erase(s.find_last_not_of(" ") + 1);
		return s;
	}
}